package com.moore.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moore.bean.Family;
import com.moore.bean.Tenant;
import com.moore.bean.TenantInfo;
import com.moore.dto.ResponseData;
import com.moore.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.moore.utils.Logger.toLog;

@Controller
@RequestMapping("/tenant")
public class TenantController {
    @Autowired
    TenantService tenantService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/reg")
    @ResponseBody
    public ResponseData reg(@RequestBody Tenant tenant){
        toLog("正在注册租客"+ tenant.getAccount());
        return tenantService.regTenant(tenant);
    }

    @RequestMapping("/saveInfo")
    @ResponseBody
    public ResponseData info(@RequestBody Map<String, Object> payload){
        toLog("正在保存租客资料");
        try {
            // 将前端传来的 basicInfo 转换为 TenantInfo 对象
            TenantInfo tenantInfo = objectMapper.convertValue(payload.get("basicInfo"), TenantInfo.class);
            // 将前端传来的 familyMembers 转换为 Family 对象列表
            List<Family> familyMembers = objectMapper.convertValue(
                    payload.get("familyMembers"),objectMapper.getTypeFactory().constructCollectionType(List.class, Family.class)
            );
            return tenantService.saveTenantInfo(tenantInfo,familyMembers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseData(500,"系统错误",null,0);
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResponseData login(@RequestBody Tenant tenant) {
        toLog(tenant.getAccount() + "正在登录");
        return tenantService.tenantLogin(tenant);
    }

    @RequestMapping("/update")
    @ResponseBody
    public ResponseData updateTenant(@RequestBody Tenant tenant){
        toLog("正在更新租客");
        return tenantService.updateTenant(tenant);
    }

    @RequestMapping("/getInfo")
    @ResponseBody
    public ResponseData getTenantInfo(@RequestBody Tenant tenant, HttpServletRequest request){
        String account = tenant.getAccount();
        toLog("正在获取租客"+account+"的信息");
        return  tenantService.queryTenantInfo(account,request);
    }

    @GetMapping("/countByMonth")
    @ResponseBody
    public ResponseData getTenantCountByMonth() {
        toLog("正在获取租客注册数量");
        return tenantService.getTenantCountByMonth();
    }
}
